#include "aht20.h"

static I2C_HandleTypeDef AHT20_Handle;

void AHT20_Init(I2C_HandleTypeDef AHT20_I2C_Handle) {
    HAL_Delay(40);
    AHT20_Handle = AHT20_I2C_Handle;

    uint8_t isCalibrate = 0;
    while(!isCalibrate){
        AHT20_Calibrate();
        isCalibrate = AHT20_ReadStatus() & 0x08;
    }
}

uint8_t AHT20_ReadStatus(){
    uint8_t rtv = 0;
    HAL_I2C_Master_Receive(&AHT20_Handle, _AHT20_READ_ADDR, &rtv, 1, 0x1000);

    return rtv;
}

void AHT20_Calibrate(){
    uint8_t sdv[3] = {0xBE, 0x08, 0x00};
    HAL_I2C_Master_Transmit(&AHT20_Handle, _AHT20_WRITE_ADDR, sdv, 3, 0x1000);
    HAL_Delay(10);
}

void AHT20_ReadData(float *humi, float *tmp) {
    uint32_t humiData, tmpData;
    uint8_t rtv[7] = {0};
    uint8_t sdv[3] = {0xAC, 0x33, 0x00};
    HAL_I2C_Master_Transmit(&AHT20_Handle, _AHT20_WRITE_ADDR, sdv, 3, 0x1000);
    HAL_Delay(80);
    HAL_I2C_Master_Receive(&AHT20_Handle, _AHT20_READ_ADDR, rtv, 7, 0x1000);

    if (rtv[0] & 0x80){
        *rh = *temp = 0;
        return;
    }

    humiData = rtv[1] << 12 | rtv[2] << 4 | (rtv[3] >> 4);
    tmpData = ((rtv[3] & 0x0f) << 16) | rtv[4] << 8 | rtv[5];
    *humi = (((float)humiData / (1 << 20)) * 100);
    *tmp = (((float)tmpData / (1 << 20)) * 200 - 50);
}


